package networkcontroller;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import controller.Controller;

/**
 * Listens for incoming tcp connnections
 * 
 * @author maciek
 * 
 */
public class TCPListener implements Runnable
{
	/**
	 * reference to controller
	 */
	Controller			ctrl;
	/**
	 * reference to network controller
	 */
	NetworkController	netCtrl;

	/**
	 * constructor which sets controller, network contoller and starts tcp
	 * listner thread
	 * 
	 * @param ctrl
	 *            controller
	 * @param netCtrl
	 *            network controller
	 */
	TCPListener(Controller ctrl, NetworkController netCtrl)
	{
		this.ctrl = ctrl;
		this.netCtrl = netCtrl;
		new Thread(this).start();
	}

	public void run()
	{
		try
		{
			ServerSocket serverSocket = new ServerSocket(NetworkConfiguration.getInstance().getPort());
			while (true)
			{
				Socket socket = serverSocket.accept();
				new TCPConnection(socket, ctrl, netCtrl);
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
